const labelService = require("../service/label.service")

const verifLabelsExist = async (ctx, next) => {
    // 1.拿到标签
    const { labels } = ctx.request.body
    // console.log(labels) //[ 'sing', 'dance' ]
    const newLabels = []
    // 2.去数据库查询标签是否存在
    for (const name of labels) {
        // console.log('name', name)
        const result = await labelService.queryLabelsByName(name)
        // console.log('result', result)
        const labelObj = { name }
        if (result) {//获取name对应label的id
            labelObj.id = result.id
            // console.log('找到了name', labelObj)
        } else {
            // console.log('没有找到name', labelObj)
            const insertResult = await labelService.create(name)
            labelObj.id = insertResult.insertId
        }
        newLabels.push(labelObj)
    }
    //3.所有的Labels都变成 [{name:爱情，id:7}，{name:友情，id:8}]
    ctx.labels = newLabels
    // console.log(newLabels)
    await next()
}
module.exports = { verifLabelsExist }